var chargingApp = angular.module("charging", []);
chargingApp.controller("chargingController", function($scope, $rootScope, $window, scCodeService, Popup, $location) {
    //转换时间函数
    function formatSeconds(value) {
        var theSecond = parseInt(value);
        var theMinute = 0;
        var theHour = 0;
        if (theSecond < 60) {
            var result = "小于" + 1 + "min";
        } else {
            if (theSecond >= 60) {
                theMinute = parseInt(theSecond / 60);
                theSecond = parseInt(theSecond % 60);

                if (theMinute >= 60) {
                    theHour = parseInt(theMinute / 60);
                    theMinute = parseInt(theMinute % 60);
                }
            }
            var result = "";
            if (theMinute > 0) {
                result = "" + parseInt(theMinute) + "min" + result;
            }
            if (theHour > 0) {
                result = "" + parseInt(theHour) + "h" + result;
            }
        }
        return result;
    }
    //时间
    $scope.startTime = localStorage.getItem("startTime");
    //获取userID
    var userId = localStorage.getItem("userId");
    //获取token
    var token = localStorage.getItem("token");
    //获取用户卡号
    var userCard = localStorage.getItem("cardNo");
    //获取服务费
    $scope.serverRate = localStorage.getItem("rate");
    // //获取充电流水号
    var chargeSn='';
    //获取chargerId和plugNo
    var chargerId = localStorage.getItem("chargerId");
    var plugNo = localStorage.getItem("plugNo"); 
    var openCharge = localStorage.getItem("openCharge");
    //獲取用戶id
                //webSocket
                var webSocket = new WebSocket("ws://" + window.location.host + "/appserver/static/websocket/" + userId);
                    webSocket.onerror = function(event) {
                        
                    };
                    webSocket.onopen = function(event) {
                        ;
                    };
                    webSocket.onmessage = function(event) {
                        ;
                        var websocketdata=JSON.parse(event.data);
                        var websocketdata_data=JSON.parse(websocketdata.data);
                        //;
                        if(websocketdata.action == "1002"){
                            chargeSn = websocketdata_data.chargeSn;
                            //alert("websocket chargeSn:"+chargeSn);
                            ;
                            localStorage.setItem("chargeSn", chargeSn);
                        }else if(websocketdata.action == "1003"){
                            var orderNo = websocketdata_data.orderNo;
                            localStorage.setItem("orderNo",orderNo);
                            //alert("websocket orderNo:"+orderNo);
                            ;
                            $scope.openCharge = "false";
                            localStorage.setItem("openCharge", $scope.openCharge);
                            window.location.href="http://" + window.location.host + "/appserver/static/wechat-ht/index.html?#/orderPay/" + orderNo;        
                        }
                        
                    };
    // alert(openCharge);
    //开启充电成功后进入此页面
    if (openCharge == "true") {
        //监听againScanController获取桩详情
        $scope.chargerDetail = JSON.parse(localStorage.getItem("chargerDetail"));
        //alert("充电中"+JSON.stringify($scope.chargerDetail));
        ;
        var plugNoList = $scope.chargerDetail.plugNoList;
        for (var i = 0; i < plugNoList.length; i++) {
            var plugNoList = plugNoList[i];
        }
        // alert($scope.chargerDetail.chargerType);
        if ($scope.chargerDetail.chargerType == "2") {
            // alert("进来了交流");
            //获取插头状态
            $scope.chargingCircle = function() {
                //计算充电时间
                var SMS = localStorage.getItem("SMS");
                var NMS = Date.parse(new Date());
                var difference = (NMS - SMS) / 1000;
                $scope.chargingTime = formatSeconds(difference);
                $scope.plugStatus = function() {
                    var postData = {
                            plugNo: plugNoList.portNo,
                            chargerId: $scope.chargerDetail.chargerId
                        }
                        // alert("桩号"+JSON.stringify($scope.chargerDetail));
                        // alert(JSON.stringify(postData));
                    scCodeService.plugStatus(postData).then(function(data) {
                        // alert(JSON.stringify(data.data));
                        $scope.plugStatusDetail = data.data;
                        // $scope.socNo = data.data.soc;
                        //alert(chargeSn);
                        chargeSn = data.data.chargeSn;

                        if (data.data.chargerV == undefined) {
                            $scope.chargerV = "220";
                        } else {
                            $scope.chargerV = data.data.chargerV;
                        }
                        if (data.data.chargeStatus == "2") {
                            $scope.openCharge = "true";
                            localStorage.setItem("openCharge", $scope.openCharge);
                        } else if(data.data.chargeStatus == "8"){
                            $scope.openCharge = "true";
                            localStorage.setItem("openCharge", $scope.openCharge);
                            Popup.notice('充电桩已离线',3000);
                        }else{
                            $scope.openCharge = "false";
                            $scope.stop = true;
                            localStorage.setItem("openCharge", $scope.openCharge);
                            localStorage.removeItem("chargerDetail");
                            var postData = {
                                userId: userId
                            }
                            Popup.notice('充电桩已停止充电', 3000, function() {
                            });
                            scCodeService.getFundList(postData).then(function(data) {
                                if (data.code == "200") {
                                    if (data.data.length !== 0) {
                                        $scope.notPayCardNo = data.data[0].orderNo;
                                         window.location.href = "http://" + window.location.host + "/appserver/static/wechat-ht/index.html?#/orderPay/" + $scope.notPayCardNo;
                                    } else {
                                        $location.path("/myOrder");
                                    }
                                }
                            })
                        }
                    })
                };
                $scope.plugStatus();
                var time = setTimeout($scope.chargingCircle, 1000 * 60);
                if ($scope.stop == true) {
                    clearTimeout(time);
                }
            }
            $scope.chargingCircle();
        }else if($scope.chargerDetail.chargerType == "1") {
            $scope.chargingCircle = function() {
                //计算充电时间
                var SMS = localStorage.getItem("SMS");
                var NMS = Date.parse(new Date());
                var difference = (NMS - SMS) / 1000;
                $scope.chargingTime = formatSeconds(difference);
                //获取插头状态
                $scope.plugStatus = function(){
                    // alert("直流插头");
                    var postData = {
                        plugNo:plugNoList.portNo,
                        chargerId:$scope.chargerDetail.chargerId
                    };
                    scCodeService.plugStatus(postData).then(function(data){
                        $scope.plugStatusDetail = data.data;
                        // alert("里面"+JSON.stringify($scope.plugStatusDetail));
                        $scope.socNo = data.data.soc;
                        // alert(chargeSn);

                        chargeSn = data.data.chargeSn;

                        if (data.data.chargerV == undefined) {
                            $scope.chargerV = "220";
                        } else {
                            $scope.chargerV = data.data.chargerV;
                        };
                        if (data.data.chargeStatus == "2") {
                            $scope.openCharge = "true";
                            localStorage.setItem("openCharge", $scope.openCharge);
                        }else if(data.data.chargeStatus == "8"){
                            $scope.openCharge = "true";
                            localStorage.setItem("openCharge", $scope.openCharge);
                            Popup.notice('充电桩已离线',3000);
                        }else{
                            $scope.openCharge = "false";
                            $scope.stop = true;
                            localStorage.setItem("openCharge", $scope.openCharge);
                            localStorage.removeItem("chargerDetail");
                            Popup.notice('充电桩已停止充电', 3000, function() {
                            });
                            var postData = {
                                userId: userId
                            };
                            scCodeService.getFundList(postData).then(function(data) {
                                if (data.code == "200") {
                                    if (data.data.length !== 0) {
                                        $scope.notPayCardNo = data.data[0].orderNo;
                                        window.location.href = "http://" + window.location.host + "/appserver/static/wechat-ht/index.html?#/orderPay/" + $scope.notPayCardNo;
                                    } else {
                                        $location.path("/myOrder");
                                    }
                                }
                            })
                        };
                        //对soc处理
                        if ($scope.socNo == undefined) {
                            $scope.socNo = 0;
                        }
                        // alert("外面"+JSON.stringify($scope.plugStatusDetail));
                        //进度条
                        var soc = $scope.socNo;
                        document.getElementById('range').value = soc;
                        var range = document.getElementById("range");
                        var rangeValue; // 滑动条获得的是度数值
                        var circle = document.getElementById("circle");
                        var circleWidth = circle.width;
                        var circleHeight = circle.height;
                        var circleContext = circle.getContext("2d");
                        var circleValue = {
                            x: 90,
                            y: 90,
                            r: 88,
                            beginAngle: -Math.PI / 2,
                            endAngle: 0
                        };
                        // 样式
                        circleContext.lineWidth = 4;
                        circleContext.strokeStyle = "#fff";
                        // 描绘进度圆环
                        function drawCircle() {
                            circleContext.restore();
                            // 清空当前路径
                            circleContext.clearRect(0, 0, circleWidth, circleHeight);
                            // 把range的度数值换成Math.PI值
                            rangeValue = Number(range.value) * 3.6;
                            // 滑动条获得的是度数值
                            circleValue.endAngle = circleValue.beginAngle + (rangeValue / 360) * 2 * Math.PI;
                            circleContext.beginPath();
                            // 绘制圆弧
                            circleContext.arc(circleValue.x, circleValue.y, circleValue.r, circleValue.beginAngle, circleValue.endAngle, false);
                            circleContext.stroke();
                            circleContext.save();
                        }
                        // 滚动条滑动动画
                        range.oninput = drawCircle;
                        drawCircle();                                                                   
                    });
                    // alert("里面2"+JSON.stringify($scope.plugStatusDetail));
                };
                $scope.plugStatus();
                //计时器
                var time = setTimeout($scope.chargingCircle, 1000 * 60);
                if ($scope.stop == true) {
                    clearTimeout(time);
                };

            }
            $scope.chargingCircle();
        }
    } else {
        window.location.href = "http://" + window.location.host + "/appserver/static/wechat-ht/scanCode.html";
    }

    // 结束充电
    $scope.closeCharge = function() {
        dialog1.style.display = "block";
        var temp = new Date();
        var Y = temp.getFullYear() + '-';
        var M = (temp.getMonth() + 1 < 10 ? '0' + (temp.getMonth() + 1) : temp.getMonth() + 1) + '-';
        var D = temp.getDate() + ' ';
        var h = temp.getHours();
        if (h < 10) {
            h = "0" + h;
        }
        var m = temp.getMinutes();
        if (m < 10) {
            m = "0" + m;
        }
        var s = temp.getSeconds();
        if (s < 10) {
            s = "0" + s;
        }
        var result = Y + M + D + h + ":" + m + ":" + s;
        // var temp = new Date();
        // var regex = /\//g;
        // var result = (temp.toLocaleDateString("zh-cn") + ' ' + temp.toLocaleTimeString("en-GB")).replace(regex, '-');
        $scope.endTime = result;
        ;
    };
    $scope.yesClose = function() {
        document.getElementById("loadingYes").style.display = "block";
        $scope.stop = true;
        var postData = {
            chargeSn: chargeSn,
            token: token,
            source: htConfig.source,
            merchantCode: htConfig.merchantCode
        }
        // alert(chargeSn);
        scCodeService.closeCharge(postData).then(function(data) {
            // alert(JSON.stringify(data));
            if (data.code == "200") {
                document.getElementById("loadingYes").style.display = "none";
                document.getElementById("loadingOrder").style.display = "block";
                dialog1.style.display = "none";
                $scope.openCharge = "false";
                localStorage.setItem("openCharge", $scope.openCharge);
                localStorage.removeItem("chargerDetail");
                // var orderNo = localStorage.getItem("orderNo");
                // alert(JSON.stringify(orderNo));
                // var num = 0;
                // var qrCodeTime = setInterval(function() {
                //     num++;
                //     if (num > 15) {
                //         ;
                //         // alert("+++");
                //         clearInterval(qrCodeTime);
                //         window.location.href = "http://weixin.mawansan.com/static/wechat-ht/index.html?#/orderPay/" + orderNo;
                //     }
                // }, 1000);
            } else {
                document.getElementById("loadingYes").style.display = "none";
                dialog1.style.display = "none";
                Popup.notice('充电桩停止充电失败', 3000, function() {

                });
            }
        })
    };
    $scope.noClose = function() {
        dialog1.style.display = "none";
    }
})
